// pages/admin/user-permission-detail/user-permission-detail.js
const { authManager } = require('../../../utils/auth');

Page({
  data: {
    userId: null,
    userName: '',
    userInfo: null,
    applications: [],
    loading: true,
    selectedApps: [],
    showBatchModal: false,
    batchAction: 'grant',
    allSelected: false
  },

  onLoad(options) {
    if (options.userId && options.userName) {
      this.setData({
        userId: options.userId,
        userName: options.userName
      });
      
      // 检查管理员权限
      if (!authManager.pageAdminCheck()) {
        return;
      }
      
      this.loadUserPermissions();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      wx.navigateBack();
    }
  },

  // 加载用户权限详情
  loadUserPermissions() {
    this.setData({ loading: true });

    wx.request({
      url: `${getApp().globalData.serverUrl}/GetUserPermissions/`,
      method: 'POST',
      data: {
        admin_username: wx.getStorageSync('username'),
        target_user_id: this.data.userId
      },
      success: (res) => {
        if (res.data.status) {
          // 预处理应用数据
          const applications = res.data.applications.map(app => ({
            ...app,
            isSelected: false,
            statusText: this.getStatusText(app),
            statusClass: this.getStatusClass(app),
            description: app.description || '暂无描述'
          }));

          this.setData({
            userInfo: res.data.user,
            applications: applications,
            loading: false,
            allSelected: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  // 获取状态文本
  getStatusText(app) {
    if (app.has_access) {
      return app.permission_source === 'user' ? '个人授权' : '角色授权';
    } else {
      return app.has_user_override ? '个人禁用' : '无权限';
    }
  },

  // 获取状态样式类
  getStatusClass(app) {
    if (app.has_access) {
      return app.permission_source === 'user' ? 'status-user-granted' : 'status-role-granted';
    } else {
      return app.has_user_override ? 'status-user-denied' : 'status-denied';
    }
  },

  // 切换应用选择状态
  toggleAppSelection(e) {
    const appId = parseInt(e.currentTarget.dataset.appId);
    const applications = this.data.applications.map(app => {
      if (app.id === appId) {
        return { ...app, isSelected: !app.isSelected };
      }
      return app;
    });

    const selectedApps = applications.filter(app => app.isSelected);
    const allSelected = applications.length > 0 && applications.every(app => app.isSelected);
    
    this.setData({
      applications: applications,
      selectedApps: selectedApps,
      allSelected: allSelected
    });
  },

  // 全选/取消全选
  toggleSelectAll() {
    const allSelected = this.data.allSelected;
    const applications = this.data.applications.map(app => ({
      ...app,
      isSelected: !allSelected
    }));

    const selectedApps = allSelected ? [] : applications.filter(app => app.isSelected);
    
    this.setData({
      applications: applications,
      selectedApps: selectedApps,
      allSelected: !allSelected
    });
  },

  // 显示批量操作模态框
  showBatchActions() {
    if (this.data.selectedApps.length === 0) {
      wx.showToast({
        title: '请先选择应用',
        icon: 'none'
      });
      return;
    }

    this.setData({ showBatchModal: true });
  },

  // 选择批量操作类型
  selectBatchAction(e) {
    const action = e.currentTarget.dataset.action;
    this.setData({ batchAction: action });
  },

  // 执行批量操作
  executeBatchAction() {
    const { selectedApps, batchAction } = this.data;
    
    if (selectedApps.length === 0) {
      wx.showToast({
        title: '请先选择应用',
        icon: 'none'
      });
      return;
    }

    const actionText = {
      'grant': '授权',
      'deny': '禁用',
      'revoke': '恢复默认'
    }[batchAction];

    wx.showModal({
      title: '确认操作',
      content: `确定要对选中的 ${selectedApps.length} 个应用执行"${actionText}"操作吗？`,
      success: (res) => {
        if (res.confirm) {
          this.performBatchAction();
        }
      }
    });
  },

  // 执行批量权限操作
  performBatchAction() {
    const { selectedApps, batchAction, userId } = this.data;
    
    const permissions = selectedApps.map(app => ({
      app_id: app.id,
      action: batchAction === 'revoke' ? 'remove' : batchAction
    }));

    wx.showLoading({ title: '处理中...' });

    wx.request({
      url: `${getApp().globalData.serverUrl}/UpdateUserPermissions/`,
      method: 'POST',
      data: {
        admin_username: wx.getStorageSync('username'),
        target_user_id: userId,
        permissions: permissions
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.status) {
          wx.showToast({
            title: '操作成功',
            icon: 'success'
          });
          this.setData({ 
            showBatchModal: false,
            selectedApps: [],
            allSelected: false
          });
          this.loadUserPermissions();
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 单个应用权限操作
  manageAppPermission(e) {
    const appId = parseInt(e.currentTarget.dataset.appId);
    const action = e.currentTarget.dataset.action;
    const app = this.data.applications.find(item => item.id === appId);
    
    if (!app) return;

    const actionText = {
      'grant': '授权',
      'deny': '禁用',
      'revoke': '恢复默认'
    }[action];

    wx.showModal({
      title: '确认操作',
      content: `确定要对应用"${app.name}"执行"${actionText}"操作吗？`,
      success: (res) => {
        if (res.confirm) {
          this.performSingleAction(appId, action);
        }
      }
    });
  },

  // 执行单个权限操作
  performSingleAction(appId, action) {
    wx.showLoading({ title: '处理中...' });

    wx.request({
      url: `${getApp().globalData.serverUrl}/UpdateUserPermissions/`,
      method: 'POST',
      data: {
        admin_username: wx.getStorageSync('username'),
        target_user_id: this.data.userId,
        permissions: [{ 
          app_id: appId, 
          action: action === 'revoke' ? 'remove' : action 
        }]
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.status) {
          wx.showToast({
            title: '操作成功',
            icon: 'success'
          });
          this.loadUserPermissions();
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 关闭批量操作模态框
  closeBatchModal() {
    this.setData({ showBatchModal: false });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡，防止点击模态框内容时关闭模态框
  }
});